//
//  CodeScanViewController.m
//  HTHappySale
//
//  Created by 创维海通 on 2017/9/21.
//  Copyright © 2017年 zxyywy. All rights reserved.
//

#import "CodeScanViewController.h"
#import "CodeScanAffirmViewController.h"

//Request
#import "HTTPPromise+Me.h"

//Model
#import "UserInfoModel.h"

//Tools
#import "AppUtil.h"

#define TopBar_Height 0
@interface CodeScanViewController ()
{
    CGSize winsize;
    
    float wScale;
    float hScale;
    
    NSArray *meetArr;
}

//@property(strong, nonatomic) AVCaptureDevice*            device;
//@property(strong, nonatomic) AVCaptureDeviceInput*       input;
//@property(strong, nonatomic) AVCaptureMetadataOutput*    output;
@property(strong, nonatomic) AVCaptureSession*           session;
@property(strong, nonatomic) AVCaptureVideoPreviewLayer* preview;

@property(nonatomic, strong) UIView*                     scanFrame;
@property(nonatomic, strong) UIView*                     line;

@property (strong, nonatomic) IBOutlet UILabel *bottomLabel;
@property (nonatomic,strong) UserInfoModel *userInfoModel;
@end

@implementation CodeScanViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    wScale = HTCFAppWidthScale;
    hScale = HTCFAppHeightScale;
    
    _bottomLabel.font = HTCFLabelFont(12 * wScale);
    
    [self initScan];
    //    [self initButton];
    [self initView];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self addNavigationLeftView:@"" andType:0];
    [self addNavigationMiddleView:@"扫一扫成为销售员"];
    
    [self scanLineAnimate];
    [_session startRunning];
}

#pragma mark -init
- (void)initScan
{
    winsize = [UIScreen mainScreen].bounds.size;
    
    //获取摄像设备
   
    NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    
    // Input
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:[devices firstObject] error:nil];
    
    // Output
    AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
    
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    // Session
    _session = [[AVCaptureSession alloc] init];
    
    [_session setSessionPreset:AVCaptureSessionPresetHigh];
    
    if ([_session canAddInput:input])
    {
        [_session addInput:input];
    }
    
    if ([_session canAddOutput:output])
    {
        [_session addOutput:output];
    }
    
    output.rectOfInterest = CGRectMake(((winsize.height - 300) / 2 - 5) / winsize.height, (winsize.width - 300) / 2 / winsize.width , 300 / winsize.height, 300 / winsize.width);
    
    // 条码类型 AVMetadataObjectTypeQRCode
    output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode, AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code];
    
    // Preview
     AVCaptureVideoPreviewLayer *layer = [AVCaptureVideoPreviewLayer layerWithSession:_session];
    self.preview = layer;
    
    _preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
    
    _preview.frame = CGRectMake(0, 0, winsize.width, winsize.height);//self.view.layer.bounds;
    
    [self.view.layer insertSublayer:_preview atIndex:0];
    
    [self.session addObserver:self forKeyPath:@"running" options:NSKeyValueObservingOptionNew context:nil];
    //开始捕获
    [self.session startRunning];
}

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context{
    if ([object isKindOfClass:[AVCaptureSession class]]) {
        BOOL isRunning = ((AVCaptureSession *)object).isRunning;
        if (isRunning) {
//            [self addAnimation];
            self.line.hidden = NO;
        }else{
//            [self removeAnimation];
            self.line.hidden = YES;
        }
    }
}

//- (void)initButton
//{
//    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(13 * wScale, 28 * hScale, 22 * hScale, 22 * hScale)];
//    [btn setImage:[UIImage imageNamed:@"fallBack"] forState:UIControlStateNormal];
//    [btn addTarget:self action:@selector(goBackVC) forControlEvents:UIControlEventTouchUpInside];
//    
//    [self.view addSubview:btn];
//}

- (void)initView
{
    CGRect frame = CGRectZero;
    
    frame.origin.x = (winsize.width - 230) / 2;//winsize.width * rect.origin.y;
    frame.origin.y = (winsize.height -360) / 2;//winsize.height * rect.origin.x;
    frame.size.width = 230;
    frame.size.height= 230;
    
    UIView* view = [[UIView alloc] initWithFrame:frame];
    view.backgroundColor= [UIColor clearColor];
    view.layer.borderWidth = 1;
    view.layer.borderColor = [[UIColor grayColor] CGColor];
    NSLog(@"viewHeight:%f",view.frame.origin.y);
    self.scanFrame = view;
    [self.view addSubview:view];
    
    //top
    UIView* shadow = [[UIView alloc] initWithFrame:CGRectMake(0, TopBar_Height, winsize.width, view.frame.origin.y - TopBar_Height)];
    shadow.backgroundColor = [UIColor blackColor];
    shadow.alpha = 0.5;
    [self.view addSubview:shadow];
    
    //bottom
    shadow = [[UIView alloc] initWithFrame:CGRectMake(0, view.frame.origin.y + view.frame.size.height, winsize.width, winsize.height - (view.frame.origin.y + view.frame.size.height))];
    shadow.backgroundColor = [UIColor blackColor];
    shadow.alpha = 0.5;
    [self.view addSubview:shadow];
    
    //left
    shadow = [[UIView alloc] initWithFrame:CGRectMake(0, view.frame.origin.y, (winsize.width - view.frame.size.width) / 2, view.frame.size.height)];
    shadow.backgroundColor = [UIColor blackColor];
    shadow.alpha = 0.5;
    [self.view addSubview:shadow];
    
    //right
    shadow = [[UIView alloc] initWithFrame:CGRectMake(view.frame.origin.x + view.frame.size.width, view.frame.origin.y, (winsize.width - view.frame.size.width) / 2, view.frame.size.height)];
    shadow.backgroundColor = [UIColor blackColor];
    shadow.alpha = 0.5;
    [self.view addSubview:shadow];
    
    _line = [[UIView alloc] initWithFrame:CGRectMake(view.frame.origin.x + 1, view.frame.origin.y + 1, frame.size.width - 2, 10)];
    //line.center = view.center;
    _line.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_line];
    
    CAGradientLayer* gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = _line.bounds;
    gradientLayer.colors = [NSArray arrayWithObjects:
                            (id)[[UIColor colorWithRed:0.9 green:0.1 blue:0.1 alpha:0.1] CGColor],
                            (id)[[UIColor colorWithRed:0.9 green:0.1 blue:0.1 alpha:0.35] CGColor],
                            (id)[[UIColor colorWithRed:0.9 green:0.1 blue:0.1 alpha:0.8] CGColor],
                            (id)[[UIColor colorWithRed:0.9 green:0.1 blue:0.1 alpha:0.35] CGColor],
                            (id)[[UIColor colorWithRed:0.9 green:0.1 blue:0.1 alpha:0.1] CGColor],
                            nil];
    [_line.layer insertSublayer:gradientLayer atIndex:0];
    
    
    UILabel *promptLabel = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH/2 - 140 * wScale, CGRectGetMaxY(self.scanFrame.frame) + 20 * hScale, 280 * wScale, 20 * hScale)];
    promptLabel.text = @"将二维码/条码放入框内,即可自动扫描";
    promptLabel.textAlignment = NSTextAlignmentCenter;
    promptLabel.textColor = HTCFQuickRGBColor(150, 150, 150);
    promptLabel.font = HTCFLabelFont(15 * wScale);
    
//    UILabel *qaCodeLabel = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH/2 - 50 * wScale , CGRectGetMaxY(promptLabel.frame) + 20 * hScale, 100 * wScale, 20 * hScale)];
//    qaCodeLabel.text = @"我的二维码";
//    qaCodeLabel.textAlignment = NSTextAlignmentCenter;
//    qaCodeLabel.textColor = HTCFQuickRGBColor(57, 184, 246);
//    qaCodeLabel.font = HTCFLabelFont(16 * wScale);
//    
//    qaCodeLabel.userInteractionEnabled = YES;
//    UITapGestureRecognizer *tag = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(NewxtWindow)];
//    [qaCodeLabel addGestureRecognizer:tag];
    
    [self.view addSubview:promptLabel];
//    [self.view addSubview:qaCodeLabel];
    
    [self initConner];
}

- (void)initConner
{
    CGFloat w = 4;
    CGFloat h = 15;
    CGFloat d = 4;
    CGPoint point = CGPointZero;
    
    //left - top
    point = CGPointMake(_scanFrame.frame.origin.x + w - d, _scanFrame.frame.origin.y - w + d);
    UIView* view = [[UIView alloc] initWithFrame:CGRectMake(point.x, point.y, w, h)];
    view.backgroundColor = HTCFQuickRGBColor(57, 184, 246);
    [self.view addSubview:view];
    
    view = [[UIView alloc] initWithFrame:CGRectMake(point.x, point.y, h, w)];
    view.backgroundColor = HTCFQuickRGBColor(57, 184, 246);
    [self.view addSubview:view];
    
    //left - down
    point = CGPointMake(_scanFrame.frame.origin.x - w + d, _scanFrame.frame.origin.y + _scanFrame.frame.size.height + d - w - h);
    view = [[UIView alloc] initWithFrame:CGRectMake(point.x, point.y, w, h)];
    view.backgroundColor = HTCFQuickRGBColor(57, 184, 246);
    [self.view addSubview:view];
    
    point = CGPointMake(point.x, _scanFrame.frame.origin.y + _scanFrame.frame.size.height - d);
    view = [[UIView alloc] initWithFrame:CGRectMake(point.x, point.y, h, w)];
    view.backgroundColor = HTCFQuickRGBColor(57, 184, 246);
    [self.view addSubview:view];
    
    //right - top
    point = CGPointMake(_scanFrame.frame.origin.x + _scanFrame.frame.size.width - d, _scanFrame.frame.origin.y - w + d);
    view = [[UIView alloc] initWithFrame:CGRectMake(point.x, point.y, w, h)];
    view.backgroundColor = HTCFQuickRGBColor(57, 184, 246);
    [self.view addSubview:view];
    
    point = CGPointMake(_scanFrame.frame.origin.x + _scanFrame.frame.size.width + w - d - h, point.y);
    view = [[UIView alloc] initWithFrame:CGRectMake(point.x, point.y, h, w)];
    view.backgroundColor = HTCFQuickRGBColor(57, 184, 246);
    [self.view addSubview:view];
    
    //right - down
    point = CGPointMake(_scanFrame.frame.origin.x + _scanFrame.frame.size.width - d, _scanFrame.frame.origin.y + _scanFrame.frame.size.height + w - d - h);
    view = [[UIView alloc] initWithFrame:CGRectMake(point.x, point.y, w, h)];
    view.backgroundColor = HTCFQuickRGBColor(57, 184, 246);
    [self.view addSubview:view];
    
    point = CGPointMake(point.x + w - h, _scanFrame.frame.origin.y + _scanFrame.frame.size.height - d);
    view = [[UIView alloc] initWithFrame:CGRectMake(point.x, point.y, h, w)];
    view.backgroundColor = HTCFQuickRGBColor(57, 184, 246);
    [self.view addSubview:view];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -<#mark#>

- (void)scanLineAnimate
{
    self.line.hidden = NO;
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:2];
    [UIView setAnimationCurve:UIViewAnimationCurveLinear];
    //[UIView setAnimationDelegate:self];
    //[UIView setAnimationDidStopSelector:@selector(didScanLineFinished)];
    [UIView setAnimationRepeatAutoreverses:YES];
    [UIView setAnimationRepeatCount:HUGE_VALF];
    _line.center = CGPointMake(_line.center.x, _scanFrame.frame.origin.y + _scanFrame.frame.size.height - 5);
    [UIView commitAnimations];
}

#pragma mark -
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    NSString *stringValue;
    
    if ([metadataObjects count] >0)
    {
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];
        
        stringValue = metadataObject.stringValue;
        
        [self requestData:[stringValue intValue]];
    }
    
//    [_delegate didCodeScanOk:stringValue];
    [_session stopRunning];
    self.line.hidden = YES;
//    [_output setMetadataObjectsDelegate:nil queue:nil];
}

#pragma mark -Request
- (void)requestData:(int)PatientNum
{
    NSDictionary *meUserParam = @{@"userId":[NSNumber numberWithInt:PatientNum]};
    NSData *jsonData;
    
    if ([NSJSONSerialization isValidJSONObject:meUserParam])
    {
        NSError *error;
        jsonData = [NSJSONSerialization dataWithJSONObject:meUserParam options:NSJSONWritingPrettyPrinted error:&error];
        NSString *json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSLog(@"json data:%@",json);
    }
    __weak __typeof(self)weakSelf = self;

    [HTTPPromise requestUser_InfoParams:jsonData Success:^(id responseObj) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        NSLog(@"%@",responseObj);
        int successRet =[responseObj[@"ret"] intValue];
        //(数据转模型）
        if (successRet == 0) {
            strongSelf.userInfoModel = [[UserInfoModel alloc] init];
            [strongSelf.userInfoModel setValuesForKeysWithDictionary:responseObj[@"info"]];
            NSLog(@"signKey :%@",strongSelf.userInfoModel.mobile);
            
            [strongSelf skipController:PatientNum];
        }else{
            [AppUtil showTipMessage:responseObj[@"desc"]];
        }
    } failure:^(NSError *error) {
        NSLog(@"%@",error.userInfo);
    }];
}

- (void)skipController:(int)PatientNum{
    CodeScanAffirmViewController *codeScanAffirmVC = [[CodeScanAffirmViewController alloc] init:_userInfoModel AtWithMesaageId:PatientNum];
    [self.navigationController pushViewController:codeScanAffirmVC animated:YES];
}

/**
 *  去除扫码动画
 */
//- (void)removeAnimation {
//    //    UIView *line = [self.view viewWithTag:self.line_tag];
//    //    [line.layer removeAnimationForKey:@"LineAnimation"];
//    //    line.hidden = YES;
//    [self.line.layer removeAnimationForKey:@"LineAnimation"];
//    self.line.hidden = YES;
//}
/**
 *  从父视图中移出
 */
- (void)selfRemoveFromSuperview {
    [self.session stopRunning];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)dealloc {
    self.line.hidden = NO;
    [self.session removeObserver:self forKeyPath:@"running"];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
